package com.dadaguai.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dadaguai.domain.SysSetting;
import com.dadaguai.dto.SystemDto.SystemSettingDto;
import com.dadaguai.enums.SysSettingCodeEnum;
import com.dadaguai.utils.SysSettingUtils;
import com.dadaguai.service.SysSettingService;
import com.dadaguai.mapper.SysSettingMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author 王半仙
 * @description 针对表【sys_setting(系统设置信息)】的数据库操作Service实现
 * @createDate 2023-10-20 11:28:40
 */
@Service
public class SysSettingServiceImpl extends ServiceImpl<SysSettingMapper, SysSetting>
        implements SysSettingService {

    public static final Logger logger = LoggerFactory.getLogger(SysSettingServiceImpl.class);

    /**
     * 加载数据库中的系统配置
     */
    @Override
    public void refreshCache() {
        try {
            SystemSettingDto systemSettingDto = new SystemSettingDto();
            List<SysSetting> list = this.list();
            for (SysSetting sysSetting : list) {
                if (sysSetting == null) continue;
                String jsonContent = sysSetting.getJsonContent();
                String jsonCode = sysSetting.getCode();
                SysSettingCodeEnum settingCodeEnum = SysSettingCodeEnum.getByCode(jsonCode);
                // 利用反射构建系统配置对象 SystemSettingDto
                PropertyDescriptor pd = new PropertyDescriptor(settingCodeEnum.getPropName(), SystemSettingDto.class);
                Method method = pd.getWriteMethod();
                Class<?> subClass = Class.forName(settingCodeEnum.getClazz());
                method.invoke(systemSettingDto, JSON.parseObject(jsonContent, subClass));
            }
            SysSettingUtils.refresh(systemSettingDto);
        } catch (Exception e) {
            logger.error("刷新缓存失败", e);
        }
    }
}




